/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ec.medical.convertidores;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrador
 */
@ManagedBean
@RequestScoped
public class MailValidator implements Validator {

    private static final Logger LOG = Logger.getLogger(MailValidator.class.getName());
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\."
            + "[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*"
            + "(\\.[A-Za-z]{2,})$";
    private Pattern pattern;
    private Matcher matcher;

    @Override
    public void validate(FacesContext fc, UIComponent uic, Object obj) throws ValidatorException {

        pattern = Pattern.compile(EMAIL_PATTERN);
        String mail = obj.toString();
        matcher = pattern.matcher(mail);

        if (!matcher.matches()) {
            FacesMessage msg =
                    new FacesMessage("El mail ingresado no posee la estructura correcta",
                    "");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }
    }

    public String validarMail(String mailUsuario) {

        pattern = Pattern.compile(EMAIL_PATTERN);
        String mail = mailUsuario;
        if (mail == null || mail.trim().length() == 0) {
            return "El Mail es un campo requerido";
        }

        matcher = pattern.matcher(mail);

        if (!matcher.matches()) {
            return "El mail ingresado no tiene la estructura correcta";
        }

        return null;
    }
}
